const express = require('express');
const fs = require('fs');
// const bodyParser = require('body-parser');
const app = express();
const Jimp = require('jimp');
app.use('/public', express.static('public'));
app.get('/', function (req, res) {
  res.redirect('/public/index.html')
});
// app.use(bodyParser.json({limit: '1mb'}));
// app.use(bodyParser.urlencoded({extended: true}));
var uploadDir='public/pic/'
var uploadDir1='public/pic1/'
function getTime() {
  var date = new Date()
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var h = date.getHours()
  var m = date.getMinutes()
  var s = date.getSeconds()
  month < 10 && (month = '0' + month)
  day < 10 && (day = '0' + day)
  h < 10 && (h = '0' + h)
  m < 10 && (m = '0' + m)
  s < 10 && (s = '0' + s)
  return `${year}-${month}-${day} ${h}:${m}:${s}`
}
app.post('/upload', function (req, res) {
  //新建一个空数组接受流的信息
  var chunks = [];
  //获取长度
  let num = 0;
  req.on("data", function (chunk) {
    chunks.push(chunk);
    num += chunk.length;
  });
  req.on("end", function () {
    //最终流的内容本体
    var buffer = Buffer.concat(chunks, num);
    //新建数组接收出去\r\n的数据下标
    let rems = [];
    let rems1 = [];
    //根据\r\n分离数据和报头
    for (var i = 0; i < buffer.length; i++) {
      let v = buffer[i];
      let v2 = buffer[i + 1];
      // 10代表\n 13代表\r
      if (v === 13 && v2 === 10) {
        rems.push(i)
        if (buffer[i+2] === 13 && buffer[i+3] === 10) {
          rems1.push(i)
        }
      }
    }
    var files = fs.readdirSync(uploadDir)
    var start=0,end=rems.indexOf(rems1[0])
    rems1.forEach((v,index)=>{
      start=end
      if(index===rems1.length-1){
        end=rems.length+1
      }else{
        end=rems.indexOf(rems1[index+1])
      }
      //获取上传图片信息
      let picmsg_1 = buffer.slice(rems[start-2] + 2, rems[start-1]).toString();
      let filename = picmsg_1.match(/filename=".*"/g)[0].split('"')[1];
      //图片数据
      // var nbuf = buffer.slice(rems[start+3] + 2, rems[rems.length - 2]);
      var nbuf = buffer.slice(rems[start+1] + 2, rems[end - 3]);
      if(files.includes(filename)){
        var index=filename.lastIndexOf('.')
        filename=(filename.slice(0,index)+Date.now()).slice(0,-3)+filename.slice(index)
      }
      // //创建空文件并写入内容
      fs.writeFile(uploadDir + filename, nbuf, function (err) {
        if (err) {
          console.log(err);
        } else {
          console.log("success")
        }
      });
      if(['jpg','png','jpeg'].includes((filename.slice(filename.lastIndexOf('.')+1)).toLowerCase())){
        Jimp.read(nbuf, (err, image) => {
          if (err) throw err;
          // 在这里进行图像压缩操作
          image.scaleToFit(200, 200).write(uploadDir1+filename, (err) => {
            if (err) throw err;
            console.log('图像压缩完成！');
          });
        });
      }
    })
    res.send({code: 0})
  });
});
app.get('/list', function (req, res) {
  var fileNameList = fs.readdirSync(uploadDir)
  res.send(fileNameList)
});
app.get('/delete', function (req, res) {
  fs.unlink(uploadDir+req.query.name,()=>{})
  fs.unlink(uploadDir1+req.query.name,()=>{})
  res.send()
});
app.get('/pic/:name', function (req, res) {
  Jimp.read(uploadDir+req.params.name, (err, image) => {
    if (err) throw err;
    // 在这里进行图像压缩操作
    image.scaleToFit(200, 200).write(outputPath, (err) => {
      if (err) throw err;
      res.send()
      console.log('图像压缩完成！');
    });
  });
});
app.listen(88);
